package com.view
{
	import com.ApplicationFacade;
	import com.model.UserProxy;
	import com.model.vo.UserVO;
	import com.view.components.UserForm;
	
	import flash.events.Event;
	
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class UserFormMediator extends Mediator implements IMediator
	{
		private var userProxy:UserProxy;
		public static const NAME:String = 'UserFormMediator';
		public function UserFormMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
			userForm.addEventListener( UserForm.ADD, onAdd );
			userForm.addEventListener( UserForm.UPDATE, onUpdate );
			userForm.addEventListener( UserForm.CANCEL, onCancel );
			
			userProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
		}
		private function get userForm ():UserForm
		{
			return viewComponent as UserForm;
		}
		
		private function onAdd( event:Event ):void
		{
			var user:UserVO = userForm.user as UserVO;
			if(userProxy.isSubmit(user))
			{
			    userProxy.addItem(user);
			    sendNotification( ApplicationFacade.USER_ADDED, user );
				clearForm();
			}
			else
			{
			    Alert.show('用户名已经注册');
			}
		}
		
		private function onUpdate( event:Event ):void
		{
			var user:UserVO = userForm.user;
			userProxy.updateItem( user );
			sendNotification(  ApplicationFacade.USER_UPDATED, user );
			clearForm();
		}
		
		private function onCancel( event:Event ):void
		{
			sendNotification(  ApplicationFacade.CANCEL_SELECTED );
			clearForm();
		}
		
		override public function listNotificationInterests():Array
		{
			return [
					ApplicationFacade.NEW_USER,
					ApplicationFacade.USER_DELETED,
					ApplicationFacade.USER_SELECTED
				   ];
		}
		
		override public function handleNotification( note:INotification ):void
		{
			switch (note.getName())
			{
				case ApplicationFacade.NEW_USER:
					userForm.user = note.getBody() as UserVO;
					userForm.mode = UserForm.MODE_ADD;
					userForm.email.setFocus();
					break;
					
				case ApplicationFacade.USER_DELETED:
					userForm.user = null;
					clearForm();
					break;
					
				case ApplicationFacade.USER_SELECTED:
					userForm.user = note.getBody() as UserVO;
					userForm.mode = UserForm.MODE_EDIT;
					userForm.email.setFocus();
					break;
					
			}
		}
		
		private function clearForm():void
		{
			userForm.username.text = '';
			userForm.email.text = ''; 
			userForm.password.text = ''; 
			userForm.confirm.text = ''; 
		}
	}
}